package com._119yn.host.gst200.database.dao.impl;

import com._119yn.host.gst200.database.dao.SysAttrDao;
import com._119yn.host.gst200.database.entity.SysAttr;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysAttrDaoImpl implements SysAttrDao {

    private final JdbcTemplate jdbcTemplate;

    @Override
    public long insert(SysAttr sysAttr) {
        String sql = "insert into SYS_ATTR (CODE, DATA) values (?, ?)";
        return jdbcTemplate.update(
                sql,
                sysAttr.getCode(),
                sysAttr.getData()
        );
    }

    @Override
    public long deleteByCode(String code) {
        String sql = "DELETE FROM SYS_ATTR WHERE CODE = ?";
        return jdbcTemplate.update(sql, code);
    }

    @Override
    public long updateByCode(SysAttr SysAttr) {
        String sql = "UPDATE SYS_ATTR SET DATA = ? WHERE CODE = ?";
        return jdbcTemplate.update(
                sql,
                SysAttr.getData(),
                SysAttr.getCode()
        );
    }

    @Override
    public SysAttr selectByCode(String code) {
        String sql = "SELECT * FROM SYS_ATTR WHERE CODE = ?";
        List<SysAttr> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SysAttr.class), code);
        if (list.isEmpty()) {
            return null;
        }
        return list.getFirst();
    }

    @Override
    public List<SysAttr> selectAll() {
        String sql = "SELECT * FROM SYS_ATTR";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SysAttr.class));
    }
}
